﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp.Caching;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Localization;
using Volo.Abp.ObjectMapping;

namespace Volo.Abp.LanguageManagement
{
    [Dependency(ReplaceServices = true)]
	public class DatabaseLanguageProvider : ITransientDependency, ILanguageProvider
	{
		public const string CacheKey = "AllLanguages";

		protected ILanguageRepository LanguageRepository { get; }

		protected IObjectMapper<LanguageManagementDomainModule> ObjectMapper { get; }

		protected IDistributedCache<LanguageListCacheItem> Cache { get; }

		public DatabaseLanguageProvider(ILanguageRepository languageRepository, IObjectMapper<LanguageManagementDomainModule> objectMapper, IDistributedCache<LanguageListCacheItem> cache)
		{
			this.LanguageRepository = languageRepository;
			this.ObjectMapper = objectMapper;
			this.Cache = cache;
		}

		public virtual async Task<IReadOnlyList<LanguageInfo>> GetLanguagesAsync()
		{
			return (await this.Cache.GetOrAddAsync(CacheKey, this.GetLanguageList)).Languages;
		}

		private async Task<LanguageListCacheItem> GetLanguageList()
		{
			var list = await this.LanguageRepository.GetListAsync(true);
			return new LanguageListCacheItem(this.ObjectMapper.Map<List<Language>, List<LanguageInfo>>(list));
		}
	}
}
